package com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ApplyChangerZQUserNameBean;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.ApplyBaseReplyDialog;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ZQUserBaseReplyDialog;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 变更债权人名称
 */
public class ApplyChangerZQUserNameActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = ApplyChangerZQUserNameActivity.class.getSimpleName();


    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    private TextView et_Name, et_socialcode, et_fddbz, et_openbank, et_countname, et_fddbrzfzm, et_chanegenote,et_applynote,et_apply_ret;
    private TextView et_Name_o, et_socialcode_o, et_fddbz_o, et_openbank_o, et_countname_o, et_fddbrzfzm_o, et_chanegenote_o;
    private RecyclerView mImgRecyclerView;

    private LinearLayout noshow_1,noshow_2,noshow_3;
    private TextView btn_commit;
    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;

    private RecyclerView mImgRecyclerView_o;

    private List<UploadImage> mImgList_o = new ArrayList<>();
    private GridImagesAdapter mImgAdapter_o;

    CommonPromptDialog mPromptDialog;
    private static ApplyChangerZQUserNameBean mInfo;

    private static int mType; //0审核 1展示

    private ApplyBaseReplyDialog dialog;

    public static void start(Context context, ApplyChangerZQUserNameBean info, int type) {
        Intent intent = new Intent(context, ApplyChangerZQUserNameActivity.class);
        mInfo = info;
        mType = type;
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_zq_rename_user);
        super.onCreate(savedInstanceState);
        titlebar_title = findViewById(R.id.top_title);
        if(mType ==0) {
            titlebar_title.setText("更改债权人名称审核");
        }else{
            titlebar_title.setText("更改债权人名称");
        }


        initViews();
        initData();


    }


    private void initViews() {
        titlebar_back = findViewById(R.id.top_back1);

        noshow_1 = findViewById(R.id.noshow_1);
        noshow_2 = findViewById(R.id.noshow_2);
        noshow_3= findViewById(R.id.noshow_3);
        et_applynote = findViewById(R.id.et_applynote);
        et_apply_ret = findViewById(R.id.et_apply_ret);

        titlebar_menu_text = findViewById(R.id.top_mune1);
        titlebar_back.setOnClickListener(this);
        titlebar_menu_text.setText("提交");
        titlebar_menu_text.setVisibility(View.INVISIBLE);

        et_Name = findViewById(R.id.et_Name);
        et_socialcode = findViewById(R.id.et_socialcode);
        et_fddbz = findViewById(R.id.et_fddbz);
        et_countname = findViewById(R.id.et_countname);
        et_fddbrzfzm = findViewById(R.id.et_fddbrzfzm);
        et_chanegenote = findViewById(R.id.et_chanegenote);
        et_openbank = findViewById(R.id.et_openbank);

        et_Name_o = findViewById(R.id.et_Name_old);
        et_socialcode_o = findViewById(R.id.et_socialcode_old);
        et_countname_o = findViewById(R.id.et_countname_old);
        et_fddbrzfzm_o = findViewById(R.id.et_fddbrzfzm_old);
        et_openbank_o = findViewById(R.id.et_openbank_old);

        titlebar_menu_text.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                saveData();
            }
        });

        btn_commit = findViewById(R.id.btn_commit);
        if (mType == 0) {
            btn_commit.setVisibility(View.VISIBLE);
            noshow_1.setVisibility(View.VISIBLE);
            noshow_2.setVisibility(View.GONE);
            noshow_3.setVisibility(View.VISIBLE);
            et_countname_o .setVisibility(View.GONE);
            et_fddbrzfzm_o.setVisibility(View.GONE);
            et_openbank_o.setVisibility(View.GONE);
            findViewById(R.id.ll_1).setVisibility(View.GONE);
            findViewById(R.id.ll_2).setVisibility(View.GONE);
            findViewById(R.id.ll_3).setVisibility(View.GONE);
        } else {
            btn_commit.setVisibility(View.GONE);
            noshow_1.setVisibility(View.GONE);
            noshow_2.setVisibility(View.VISIBLE);
            noshow_3.setVisibility(View.GONE);
        }

        btn_commit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new ApplyBaseReplyDialog(ApplyChangerZQUserNameActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save) {
                            String msg = dialog.text_reason.getText().toString().trim();
                            String status = "1";
                            if (dialog.cb_nopass.isChecked()) {
                                status = "2";
                            }
                            String notifyTypes = "";
                            if (dialog.send_msg.isChecked() && dialog.send_phone.isChecked()) {
                                notifyTypes = "0,1";
                            } else if (dialog.send_msg.isChecked()) {
                                notifyTypes = "0";
                            } else {
                                notifyTypes = "1";
                            }


//                    addZQUser(name,phone);
                            applyPerson(status, msg, notifyTypes);
                            dialog.dismiss();
                        }
                        if (v.getId() == R.id.btn_chancel) {
                            dialog.dismiss();
                        }

                    }
                });
                dialog.show();
            }
        });



//        mImgRecyclerView_o = findViewById(R.id.recycler_imgs_old);
//        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
//        mImgRecyclerView_o.setLayoutManager(manager);
//        mImgAdapter_o = new GridImagesAdapter(this, TYPE_PREVIEW);
//        mImgAdapter_o.setList(mImgList_o);
//        mImgRecyclerView_o.setAdapter(mImgAdapter_o);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new GridImagesAdapter(this, TYPE_PREVIEW);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);
        mImgAdapter.setEnable(false);

        if (mInfo != null) {
//            et_Name.setText(mInfo.getCreditorName());
//            et_socialcode.setText(mInfo.getSocialUniformCreditCode());
//            et_fddbz.setText(mInfo.getLegalRepresentativeName());
            if (mInfo.getCreditorInfo() != null) {
                et_Name_o.setText( Utils.tmpString(mInfo.getCreditorInfo().getCreditorName()));
                et_socialcode_o.setText( Utils.tmpString(mInfo.getCreditorInfo().getSocialUniformCreditCode()));
//                et_fddbz.setText( mInfo.getChange().());
                et_countname_o.setText( Utils.tmpString(mInfo.getCreditorInfo().getBankAccountName()));
                et_openbank_o.setText( Utils.tmpString(mInfo.getCreditorInfo().getBank()));
                et_fddbrzfzm_o.setText( Utils.tmpString(mInfo.getCreditorInfo().getBankAccount()));

            }

            if (mInfo.getChange() != null) {
                et_Name.setText( Utils.tmpString(mInfo.getChange().getCreditorName()));
                et_socialcode.setText( Utils.tmpString(mInfo.getChange().getSocialUniformCreditCode()));
//                et_fddbz.setText( mInfo.getChange().());
                et_countname.setText( Utils.tmpString(mInfo.getChange().getBankAccountName()));
                et_openbank.setText( Utils.tmpString(mInfo.getChange().getBank()));
                et_fddbrzfzm.setText( Utils.tmpString(mInfo.getChange().getBankAccount()));

                et_chanegenote.setText( Utils.tmpString(mInfo.getChange().getChangeDetail()));

                for (int i = 0; i < mInfo.getChange().getProveFileJson().size(); i++) {
                    TaskAtta atta = mInfo.getChange().getProveFileJson().get(i);
                    JSONObject obj = new JSONObject();
                    try {
                        obj.putOpt("filename", atta.getAttachmentName());
                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                        obj.putOpt("filesize", atta.getAttachmentSize());
                        obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                        mImgList.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if(mType ==1)
                {
                    et_applynote.setText( Utils.tmpString(mInfo.getChange().getAuditDetail()));
                    et_apply_ret.setText( Utils.tmpString(mInfo.getChange().getAuditStatus().getText()));
                }

            }
        }



    }

    @Override
    public void initData() {


    }

    private boolean showflag = true;

    @Override
    public void onBackPressed() {
        finish();
//        super.onBackPressed();
//        findViewById(R.id.titlebar_back).performClick();
//        findViewById(R.id.titlebar_back).performClick();
//        noticeDialog = new PublicNoticeDialog(ApplyChangerZQUserNameActivity.this, new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (v.getId() == R.id.btn_save_notice) {
//                    finish();
//                    noticeDialog.dismiss();
//                } else {
//                    noticeDialog.dismiss();
//                }
//            }
//        }, 1, "提示", "放弃编辑？",
//                "否", "是");
//        noticeDialog.show();
    }


    private PublicNoticeDialog noticeDialog;

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.titlebar_menu_text:
//                saveData();
                break;
            case R.id.top_back1:
                finish();
//                noticeDialog = new PublicNoticeDialog(ApplyChangerZQUserNameActivity.this, new OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (v.getId() == R.id.btn_save_notice) {
//                            finish();
//                            noticeDialog.dismiss();
//                        } else {
//                            noticeDialog.dismiss();
//                        }
//                    }
//                }, 1, "提示", "放弃编辑？",
//                        "否", "是");
//                noticeDialog.show();
                break;
            default:
                break;
        }
    }

    public void applyPerson(String status, String msg, String notifyTypes) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

//        String no = zqUserDetailInfo.get(0).getId();
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
//                .add("creditorId", creditorId)
                .add("auditState", status)
                .add("auditDesc", msg)
                .add("noticeTypes", notifyTypes)
                .add("projectId", mInfo.getChange().getBankruptcyProjectId())
                .add("changeId", mInfo.getChange().getId())
                .add("auditType", "3")
                .build();

        String url = Consts.WEBURL_RIGHTSAUDIT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ApplyChangerZQUserNameActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
//

                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                ToastUtil.getInstance(ApplyChangerZQUserNameActivity.this).showShortToast("审核完成");
                                finish();
//                                Toast.makeText(ApplyChangerZQUserNameActivity.this, "替吉奥成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ApplyChangerZQUserNameActivity.this, "保存失败" + object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ApplyChangerZQUserNameActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }



}

